package com.shuzi.MediaShare.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import android.net.wifi.WifiManager;
import android.os.Handler;

import com.shuzi.MediaShare.Constant;
import com.shuzi.MediaShare.gui.login.LoginActivity;
import com.shuzi.MediaShare.utils.Logger;

/**
 * udp广播获取地址
 * 
 * @author lung 下午10:49:29 2013
 */
public class UDPBoardCast
{

	private static UDPBoardCast udpBoardCast = null;

	static String destAddressStr = "255.255.255.255";

	// static String destAddressStr = "192.168.1.101";

	static final int destPortInt = 12345;

	static int TTLTime = 4;

	private String msg = "discover";

	/**
	 * 获取单例
	 * 
	 * @return
	 */
	public static UDPBoardCast getInstance()
	{
		if (udpBoardCast == null)
		{
			udpBoardCast = new UDPBoardCast();
		}
		return udpBoardCast;
	}

	/**
	 * 发送udp广播获取ip
	 */
	public void sentBoardCast(final Handler handler)
	{

		handler.postDelayed(new Runnable()
		{

			@Override
			public void run()
			{
				if (!Protocol.getUdpIp)
				{
					handler.sendEmptyMessage(LoginActivity.FAILED_GET_IP);
				}

			}
		}, 5000);
		new Thread(new Runnable()
		{

			@Override
			public void run()
			{
				InetAddress destAddress = null;
				try
				{
					destAddress = InetAddress.getByName(destAddressStr);
				} catch (UnknownHostException e1)
				{
					e1.printStackTrace();
					handler.sendEmptyMessage(LoginActivity.FAILED_GET_IP);
				}

				try
				{
					DatagramSocket theSocket = new DatagramSocket();
					byte[] sendMSG = msg.getBytes();
					DatagramPacket dp = new DatagramPacket(sendMSG,
							sendMSG.length, destAddress, destPortInt);

					DatagramSocket socket = new DatagramSocket(destPortInt);

					theSocket.send(dp);
					Logger logger = Logger.getLogger();
					logger.v("lung", "send brocast = ");
					theSocket.close();

					byte[] buf = new byte[1024];
					DatagramPacket datagramPacket = new DatagramPacket(buf,
							buf.length);

					int count = 0;
					while (count < 10)
					{
						socket.receive(datagramPacket);
						String result = new String(buf, 0, buf.length);
						String ipString = datagramPacket.getAddress()
								.getHostAddress().toString();
						logger.v("lung", "result = " + result + "address ="
								+ ipString);
						if (!ipString.equals(Constant.Ip))
						{
							count = 100;
							Protocol.BASEPATH = "http://" + ipString;
							handler.sendEmptyMessage(LoginActivity.SUCCESS_GET_IP);
							return;
						}
						count++;
					}

					socket.close();

					//handler.sendEmptyMessage(LoginActivity.FAILED_GET_IP);
					// if (result != null && !result.equals(""))
					// {
					// Protocol.BASEPATH = "http://"
					// + result.substring(0, result.indexOf("@"))
					// .replace("discover_reply#", "") + ":81";
					// logger.v("lung", "Protocol.BASEPATH="
					// + Protocol.BASEPATH);
					//
					// handler.sendEmptyMessage(LoginActivity.SUCCESS_GET_IP);
					// } else
					// {
					// handler.sendEmptyMessage(LoginActivity.FAILED_GET_IP);
					// }

				} catch (IOException e)
				{
					e.printStackTrace();
					handler.sendEmptyMessage(LoginActivity.FAILED_GET_IP);
				}

			}
		}).start();
	}
}
